/* eslint-disable no-unused-vars */
import { BattleData } from '@/types/process'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

// 文本状态接口
export interface TextState {
  texts: { id: string; data: BattleData }[]
  addText: (id: string, data: BattleData) => void
  removeText: (id: string) => void
  containsText: (id: string) => boolean
}

// 检查 localStorage 是否可用
const isLocalStorageAvailable = () => {
  try {
    const testKey = '__test__'
    localStorage.setItem(testKey, testKey)
    localStorage.removeItem(testKey)
    return true
  } catch (e) {
    return false
  }
}
// 创建一个自定义的存储，带有过期逻辑
const createExpiringStorage = (storage: Storage, expireIn: number) => {
  return {
    getItem: (name: string) => {
      const item = storage.getItem(name)
      if (!item) return null

      const { value, expiry } = JSON.parse(item, (key, value) =>
        typeof value === 'string' && /^\d+n$/.test(value)
          ? BigInt(value.slice(0, -1))
          : value
      )
      if (Date.now() > expiry) {
        storage.removeItem(name)
        return null
      }
      return value
    },
    setItem: (name: string, value: unknown) => {
      const expiry = Date.now() + expireIn
      const item = JSON.stringify({ value, expiry }, (key, value) =>
        typeof value === 'bigint' ? value.toString() + 'n' : value
      )
      storage.setItem(name, item)
    },
    removeItem: (name: string) => {
      storage.removeItem(name)
    }
  }
}

// 创建文本状态
export const battleDataStore = create<TextState>()(
  persist(
    (set, get) => ({
      texts: [],
      addText: (id: string, data: BattleData) => {
        set((state) => {
          const newTexts = [...state.texts, { id, data }]
          if (newTexts.length > 30) {
            newTexts.shift() // 删除最早添加的文本
          }
          return { texts: newTexts }
        })
      },
      removeText: (id: string) => {
        set((state) => ({
          texts: state.texts.filter((text) => text.id !== id)
        }))
      },
      containsText: (id: string) => {
        return get().texts.some((text) => text.id === id)
      }
    }),
    {
      name: 'battle_data_v2',
      // storage: createJSONStorage(() => sessionStorage)
      storage: isLocalStorageAvailable()
        ? createExpiringStorage(localStorage, 7 * 24 * 60 * 60 * 1000)
        : undefined
    }
  )
)
